<template>
  <div>
    <el-form ref="assetForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-divider content-position="left">基本信息</el-divider>
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formItem.name" placeholder="请输入名称" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="资产编码" prop="code">
            <el-input v-model="formItem.code" disabled placeholder="" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产分类" prop="smallTypeCode">
            <treeselect
              v-model="formItem.smallTypeCode"
              :multiple="false"
              :options="typeOptions"
              placeholder="选择资产分类"
              :disable-branch-nodes="true"
              @input="inputType"
              @select="selectType"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="原始编码" prop="originalCode">
            <el-input v-model="formItem.originalCode" placeholder="请输入" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="购置日期" prop="purchaseDate">
            <el-date-picker
              v-model="formItem.purchaseDate"
              type="date"
              placeholder="选择购置日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="formItem.brand" placeholder="请输入品牌" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格型号" prop="specifications">
            <el-input v-model="formItem.specifications" placeholder="请输入规格型号" :maxlength="255">
              <el-button slot="append" icon="el-icon-search" @click="productSelDialogFormVisible=true" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="序列号" prop="serialnumber">
            <el-input v-model="formItem.serialnumber" placeholder="请输入序列号" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="合同" prop="contractName">
            <el-input v-model="formItem.contractName" placeholder="请选择合同" @focus="contractFormVisible = true" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="供应商" prop="supplierName">
            <el-autocomplete v-model="formItem.supplierName" style="width: 100%;" :fetch-suggestions="querySearch" placeholder="请输入供应商" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="金额" prop="money">
            <el-input-number v-model="formItem.money" :precision="2" :step="1" :max="1000000000" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计量单位" prop="measureUnit">
            <el-input v-model="formItem.measureUnit" placeholder="请输入计量单位" :maxlength="255" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider v-if="!isConsumption" content-position="left">维保信息</el-divider>
      <el-row v-if="!isConsumption" :gutter="40">
        <el-col :span="12">
          <el-form-item label="维保开始">
            <el-date-picker
              v-model="formItem.maintenanceStartTime"
              type="date"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维保结束">
            <el-date-picker
              v-model="formItem.maintenanceEndTime"
              type="date"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">其它信息</el-divider>
      <el-row :gutter="40">
        <!-- <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formItem.status" class="select_input" placeholder="请选择状态">
              <el-option v-for="(item) in ASSET_STATUS" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item :label="isConsumption ? '仓库位置' : '位置'" prop="location">
            <treeselect
              v-model="formItem.location"
              :multiple="false"
              :options="myLocations"
              :disable-branch-nodes="true"
              placeholder="请选择位置"
              @input="inputLocation"
              @select="selectLocation"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="机房" prop="computerRoom">
            <el-input v-model="formItem.computerRoom" placeholder="请输入机房" :maxlength="255" cl />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机柜" prop="cabinet">
            <el-input v-model="formItem.cabinet" placeholder="请输入存放机柜" :maxlength="255" cl />
          </el-form-item>
        </el-col>
        <!-- <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="使用部门" prop="managementOrgCode">
            <treeselect
              v-model="formItem.managementOrgCode"
              :multiple="false"
              :options="availableOganizations"
              placeholder="选择使用部门"
              :disable-branch-nodes="true"
              @input="inputOrg"
              @select="selectOrg"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="使用人" prop="managementUserCode">
            <el-select v-model="formItem.managementUserCode" class="select_input" filterable clearable placeholder="请选择使用人">
              <el-option v-for="(item) in orgUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col v-if="isConsumption" :span="12">
          <el-form-item label="数量" prop="amount">
            <el-input-number v-model="formItem.amount" :precision="0" :step="1" :max="1000000000" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="使用期限" prop="usePeriod">
            <el-input v-model="formItem.usePeriod" placeholder="请输入使用期限" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isConsumption" :span="12">
          <el-form-item label="用途" prop="purpose">
            <el-input v-model="formItem.purpose" placeholder="请输入用途" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="note">
            <el-input v-model="formItem.note" placeholder="请输入备注" :maxlength="255" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog v-if="manucacturerSelect" title="选择供应商" :append-to-body="true" :show="manucacturerSelect" @on-ok="selectManufaturerOk" @on-cancel="manucacturerSelect = false">
      <manufacturer ref="manfacturer" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
    <SelectDialog v-if="contractFormVisible" title="选择合同" :append-to-body="true" :show="contractFormVisible" @on-ok="selectContractOk" @on-cancel="contractFormVisible = false">
      <contract ref="contract" :for-selection="false" :multiple-selected="true" :belongs="belongs" />
    </SelectDialog>
    <SelectDialog v-if="productSelDialogFormVisible" title="选择产品档案" :show="productSelDialogFormVisible" :append-to-body="true" @on-ok="selectProductOk" @on-cancel="productSelDialogFormVisible = false">
      <product ref="type" :for-selection="true" :categories="categories" :asset-type-code="formItem.assetTypeCode" :multiple-selected="true" :belongs="belongs" />
    </SelectDialog>
  </div>
</template>

<script>
import treeselect from '@neu/biz-core/components/TreeSelect'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import { tree as typeTree } from '@neu/dcam-ui/api/assetType'
import { tree as locationTree } from '@neu/dcam-ui/api/location'
import manufacturer from '@neu/dcam-ui/views/manufacturer/tables'
import contract from '@neu/dcam-ui/views/contract'
import product from '@neu/dcam-ui/views/product'
import { formatDate } from '@neu/biz-core/utils/utils'
import { tree as orgTree } from '@neu/auth-ui/api/organization'
import { list, getAllKjUsers } from '@neu/auth-ui/api/user'
import belongs from '@neu/dcam-ui/mixins/belongs'
import { ASSET_STATUS } from '@neu/dcam-ui/utils/constants'
import { list as getAllStorehouse } from '@neu/dcam-ui/api/storehouse'
import { list as getAllManufacturer } from '@neu/dcam-ui/api/manufacturer'

// 定义一个表单原始项
const formItem = {
  /** 资产名称 */
  name: '',
  /** 资产编号 */
  code: '',
  /** 原始资产编号 */
  originalCode: '',
  /** 购置日期 */
  purchaseDate: null,
  /** 供应商ID */
  supplierId: '',
  /** 供应商名称 */
  supplierName: '',
  /** 品牌 */
  brand: '',
  /** 规格型号 */
  specifications: '',
  /** 序列号 */
  serialnumber: '',
  /** 机房 */
  computerRoom: '',
  /** 位置编码 */
  location: null,
  /** 机柜 */
  cabinet: '',
  /** 维保开始时间 */
  maintenanceStartTime: null,
  /** 维保结束时间 */
  maintenanceEndTime: null,
  /** 位置 */
  locationName: '',
  /** 大类型名称 */
  bigTypeName: '',
  /** 大类型编码 */
  bigTypeCode: '',
  /** 中类型名称 */
  middleTypeName: '',
  /** 中类型编码 */
  middleTypeCode: '',
  /** 小类型名称 */
  smallTypeName: '',
  /** 小类型编码 */
  smallTypeCode: null,
  /** 合同号 */
  contractNo: '',
  /** 合同名称 */
  contractName: '',
  /** 计量单位 */
  measureUnit: '',
  /** 数量 */
  amount: 1,
  /** 金额 */
  money: 0.00,
  /** 使用期限 */
  usePeriod: '',
  /** 经办人 */
  agent: '',
  /** 备注 */
  note: '',
  /** 管理部门名称 */
  managementOrgName: '',
  /** 管理部门编码 */
  managementOrgCode: null,
  /** 管理人编码 */
  managementUserCode: '',
  /** 管理人名称 */
  managementUserName: '',
  /** 所属 */
  belongs: '',
  /** 类别 */
  categories: '',
  /** 资产卡片 */
  card: '',
  /** 用途 */
  purpose: '',
  /** 状态 */
  status: 'unused',
  /** 状态 */
  locked: false
}
export default {
  name: 'AssetForm',
  components: {
    manufacturer,
    SelectDialog,
    contract,
    treeselect,
    product
  },
  mixins: [belongs],
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      /** 规格型号disable */
      productNameDisabled: true,
      /** 是否显示产品信息 */
      productSelDialogFormVisible: false,
      /** 是否显示合同信息 */
      contractFormVisible: false,
      /** 维保信息对话框是否显示 */
      manucacturerSelect: false,
      /** 资产位置树 */
      availableLocations: [],
      /** 资产类型树 */
      typeOptions: [],
      /** 使用部门 */
      availableOganizations: [],
      /** 是否初始化 */
      isUpdateInit: true,
      /** 使用人集合 */
      orgUsers: [],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        smallTypeCode: [{ required: true, message: '资产分类不能为空', trigger: 'change' }],
        purchaseDate: [{ required: true, message: '购置日期不能为空', trigger: 'blur' }]
      },
      ASSET_STATUS,
      /** 所有仓库 */
      storehouses: [],
      manufacturers: []
    }
  },
  computed: {
    isConsumption: function() {
      return this.categories === '3'
    },
    myLocations: function() {
      if (this.categories === '3') {
        const flatTree = this.flattenTreeDataClosure(this.availableLocations)
        return this.storehouses.filter(it => !!flatTree.find(n => n.code === it.locationCode)).map(it => {
          return {
            code: it.locationCode,
            title: it.locationName
          }
        })
      } else {
        return this.availableLocations
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {
    // 类型树
    typeTree(this.belongs, this.categories).then(response => {
      const result = response.data
      this.typeOptions = result
    })
    // 位置树
    locationTree(this.belongs).then(response => {
      this.availableLocations = response.data
    })
    // 管理部门树
    orgTree(this.belongs).then(response => {
      this.availableOganizations = [response.data]
    })
    getAllStorehouse().then(response => {
      this.storehouses = response.data
    })
    getAllManufacturer().then(response => {
      this.manufacturers = response.data.map(m => {
        return {
          value: m.name
        }
      })
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        this.isUpdateInit = false
        this.formItem = this.$parent.$parent.$parent.selectRow
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 类型选择
    selectType(obj) {
      this.formItem.smallTypeName = obj.title || ''
    },
    // 类型选择
    inputType(value) {
      if (!value) {
        this.formItem.smallTypeName = ''
      }
    },
    // 位置选择
    selectLocation(obj) {
      this.formItem.locationName = obj.title || ''
    },
    // 位置选择
    inputLocation(value) {
      if (!value) {
        this.formItem.locationName = value || ''
      }
    },
    /** 组织机构赋值 */
    selectOrg(value) {
      this.formItem.managementOrgName = value.title || ''
    },
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.orgUsers = []
        this.formItem.managementUserCode = ''
        this.formItem.managementUserName = ''
      }

      this.isUpdateInit = true
      if (!value) {
        this.formItem.managementOrgName = value || ''
      }
      if (value === 'kj') {
        getAllKjUsers().then(res => {
          this.orgUsers = res.data
        })
      } else {
        // 查询部门下面的人员
        list({ s_orgCode: value }).then(res => {
          this.orgUsers = res.data
        })
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      return new Promise(resolve => {
        this.$refs.assetForm.validate((valid) => {
          if (valid) {
            if (formatDate(this.formItem.maintenanceStartTime) > formatDate(this.formItem.maintenanceEndTime)) {
              return this.$message({
                showClose: true,
                message: '维保开始时间大于维保结束时间',
                type: 'error'
              })
            }
            const saveData = { ...this.formItem }

            if (saveData.maintenanceStartTime) {
              saveData.maintenanceStartTime = new Date(saveData.maintenanceStartTime).getTime()
            }

            if (saveData.maintenanceEndTime) {
              saveData.maintenanceEndTime = new Date(saveData.maintenanceEndTime).getTime()
            }

            if (saveData.purchaseDate) {
              saveData.purchaseDate = new Date(saveData.purchaseDate).getTime()
            }

            // 管理人
            const one = this.orgUsers.find(e => e.username === saveData.managementUserCode)
            saveData.managementUserName = one ? one.name : ''

            const result = this.flattenTreeDataClosure(this.typeOptions)
            const trees = this.findParent(saveData.smallTypeCode, result)

            if (trees[0]) {
              saveData.bigTypeName = trees[0].name
              saveData.bigTypeCode = trees[0].code
            }

            if (trees[1]) {
              saveData.middleTypeName = trees[1].name
              saveData.middleTypeCode = trees[1].code
            }

            saveData.belongs = this.belongs
            saveData.categories = this.categories

            // saveData.id = this.id
            resolve(saveData)
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.assetForm.resetFields()
      this.formItem = { ...formItem }
    },
    /** 选择供应商弹窗确认 */
    selectManufaturerOk() {
      var manufacturers = this.$refs.manfacturer.selections
      if (manufacturers.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个供应商',
          type: 'error'
        })
      }
      if (manufacturers.length < 1) {
        this.formItem.supplierId = ''
        this.formItem.supplierName = ''
      } else {
        this.formItem.supplierId = manufacturers[0].id
        this.formItem.supplierName = manufacturers[0].name
      }

      this.manucacturerSelect = false
    },

    /** 合同弹窗确认OK */
    selectContractOk() {
      var selectContract = this.$refs.contract.selections
      if (selectContract.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个合同',
          type: 'error'
        })
      }
      if (selectContract.length < 1) {
        this.formItem.contractName = ''
        this.formItem.contractNo = ''
      } else {
        this.formItem.contractName = selectContract[0].name
        this.formItem.contractNo = selectContract[0].code
      }
      this.contractFormVisible = false
    },
    // 产品档案选择OK
    selectProductOk() {
      const selections = this.$refs.type.selections
      if (selections.length !== 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个产品档案',
          type: 'error'
        })
      } else {
        // 规格型号
        this.formItem.specifications = selections[0].specification
        // 原值
        this.formItem.money = selections[0].money
        this.formItem.brand = selections[0].brand
        this.productSelDialogFormVisible = false
      }
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    findParent(item, flattenTree) {
      const parentArr = [] // 存储所有的父级元素
      function find(item, flattenTree) {
        flattenTree.forEach(ele => {
          if (ele.code === item) {
            parentArr.unshift({ code: ele.code, name: ele.title })
            find(ele.parentKey, flattenTree)
          }
        })
      }
      find(item, flattenTree)
      return parentArr
    },
    querySearch(queryString, cb) {
      const manufacturers = this.manufacturers
      const results = queryString ? manufacturers.filter(this.createFilter(queryString)) : manufacturers
      cb(results)
    },
    createFilter(queryString) {
      return (m) => {
        return (m.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
      }
    }
  }
}
</script>

